import { LinRouter, NotFound, disableLoading } from "lin-mizar";
import { groupRequired } from "../../middleware/jwt";
import {
  BookSearchValidator,
  CreateOrUpdateBookValidator,
} from "../../validator/book";
const schedule = require("node-schedule");
import {
  TaskSearchValidator,
  CreateOrUpdateTaskValidator,
} from "../../validator/task";

import { PositiveIdValidator } from "../../validator/common";
import { test } from "../../middleware/index";
import { getSafeParamId } from "../../lib/util";
import { BookNotFound } from "../../lib/exception";
import { TaskDao } from "../../dao/task";
import { emailTo } from "../../lib/email";
import { arr } from "../../config/email-list";

// course 的红图实例
const taskApi = new LinRouter({
  prefix: "/v1/task",
  module: "任务",
});

// course 的dao 数据库访问层实例
const TaskDto = new TaskDao();

if (!global.taskList) {
  global.taskList = [];
}

taskApi.get("/:id", async (ctx) => {
  const v = await new PositiveIdValidator().validate(ctx);
  const id = v.get("path.id");
  const task = await TaskDto.getTask(id);
  if (!task) {
    throw new NotFound({
      code: 10022,
    });
  }
  ctx.json(task);
});

taskApi.get("/job/list", async (ctx) => {
  console.log(schedule.scheduledJobs);
  // ctx.json(schedule.scheduledJobs);
  console.log(global.taskList[0].cancel());
  ctx.response.body = "123";
});

taskApi.get("/crawler", async (ctx) => {
  ctx.response.body = "123";
});

taskApi.get("/", async (ctx) => {
  const tasks = await TaskDto.getTasks();

  // console.log(job.name, job2.name);

  if (!tasks || tasks.length < 1) {
    throw new NotFound({
      message: "没有找到任务",
    });
  } else {
    if (global.taskList.length == 0) {
      test();
    }
  }
  ctx.json(tasks);
});

// 初始化任务

taskApi.get("/search/one", async (ctx) => {
  const v = await new BookSearchValidator().validate(ctx);
  const task = await TaskDto.getTaskByKeyword(v.get("query.q"));
  if (!task) {
    throw new BookNotFound();
  }
  ctx.json(task);
});

taskApi.post("/", async (ctx) => {
  const v = await new CreateOrUpdateTaskValidator().validate(ctx);
  const data = await TaskDto.createTask(v);
  let to = v.get("body.to");
  let name = v.get("body.name");
  let info = v.get("body.info");
  const job = schedule.scheduleJob("42 * * * * *", async function () {
    await emailTo(to, name, "", info, function (b) {
      console.log(b, "info");
    });
    console.log("The answer to life, the universe, and everything!1111");
  });
  let obj = {
    id: data.dataValues.id,
    job,
  };
  global.taskList.push(obj);
  ctx.success({
    code: 16,
  });
});

taskApi.get("/send/one", async (ctx) => {
  let html = `<h1>市面收费IT课程免费领取，来就送。需要的可以看一下</h1>
  选课地址：<a href="https://www.yuque.com/chenxiaoqiang-brnye/itbao">点这里</a><br />
  <span>极客时间专栏8元一门，打包68元，慕课实战低至9.9</span>
  <a href="https://javacm.com">网站选课点这里,首次免费领课</a><br />
  大致内容目录：
  <ul>
    <li><a href="https://www.yuque.com/chenxiaoqiang-brnye/itbao">慕课网点这里</a></li>
    <li><a href="https://www.yuque.com/chenxiaoqiang-brnye/itbao">极客时间点这里</a></li>
    <li><a href="https://www.yuque.com/chenxiaoqiang-brnye/itbao">前端点这里</a></li>
    <li><a href="https://www.yuque.com/chenxiaoqiang-brnye/itbao">GO点这里</a></li>
  </ul>
  课程类型

  <div>客服微信：cbq2393159</div>
  <div style='color:red;font-weight:800;'>首次添加，都会赠送实战课程。感谢您的支持，如有打扰，十分抱歉。</div>
  `;

  for (var i = 0; i < arr.length; i += 30) {
    let result = [];
    result.push(arr.slice(i, i + 30));
    let qq = result
      .map((item) => {
        return item + "@qq.com";
      })
      .join(",");
    await emailTo(
      qq,
      "打扰一下，没有恶意，推荐一个资源,首次访问可以获取网上付费学习资料。",
      "",
      html,
      function (b) {
        console.log(b, "info");
      }
    );
  }

  console.log("end");
  // emailTo(qq, '您好，同学我这边有很多网课IT资源，首次加我免费赠送课，自己挑选哦。', '', html, function (a) {
  //   console.log(a, '完成')
  // })
  ctx.success({
    code: 12,
  });
});

taskApi.put("/:id", async (ctx) => {
  const v = await new CreateOrUpdateTaskValidator().validate(ctx);
  const id = getSafeParamId(ctx);
  const data = await TaskDto.updateTask(v, id);

  // 删除之前的任务
  global.taskList
    .filter((item) => {
      return item.id == id;
    })[0]
    .job.cancel();

  global.taskList = global.taskList.filter((item) => {
    return item.id != id;
  });
  let to = data.dataValues.to;
  let name = data.dataValues.name;
  let info = data.dataValues.name.info;
  const job = schedule.scheduleJob("42 * * * * *", async function () {
    await emailTo(to, name, "", info, function (b) {
      console.log(b, "info");
    });
    console.log(to, "发送");
  });
  let obj = {
    id: data.dataValues.id,
    job,
  };
  global.taskList.push(obj);

  ctx.success({
    code: 13,
  });
});

taskApi.linDelete(
  "deleteTask",
  "/:id",
  taskApi.permission("删除资源"),
  groupRequired,
  async (ctx) => {
    const v = await new PositiveIdValidator().validate(ctx);
    const id = v.get("path.id");
    await TaskDto.deleteTask(id);

    global.taskList
      .filter((item) => {
        return item.id == id;
      })[0]
      .job.cancel();

    global.taskList = global.taskList.filter((item) => {
      return item.id != id;
    });

    ctx.success({
      code: 14,
    });
  }
);

module.exports = { taskApi, [disableLoading]: false };
